package leetcode;

import util.Tree;
import util.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0113.java
 * @Author : WangRuoyu
 * @Date 2023/11/11 21:13
 */


public class Q0113 {
    List<Integer> tmp = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();

    private void dfs(TreeNode root, int targetSum, int sum) {
        if (root.left == null && root.right == null) {
            if (sum + root.val == targetSum) {
                tmp.add(root.val);
                res.add(new ArrayList<>(tmp));
                tmp.remove(tmp.size() - 1);
            }
            return;
        }
        if (root.left != null) {
            tmp.add(root.val);
            dfs(root.left, targetSum, sum + root.val);
            tmp.remove(tmp.size() - 1);
        }
        if (root.right != null) {
            tmp.add(root.val);
            dfs(root.right, targetSum, sum + root.val);
            tmp.remove(tmp.size() - 1);
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) return res;
        dfs(root, targetSum, 0);
        return res;
    }

    public static void main(String[] args) {
        Q0113 sl = new Q0113();
        String[] nodes = {"5", "4", "11", "7", null, null, "2", null, null, null, "8", "13", null, null, "4", "5", null, null, "1", null, null};
        TreeNode root = Tree.createTreeByPreorder(nodes);
        int targetSum = 22;
        System.out.println(sl.pathSum(root, targetSum));
    }
}